package logic.nodes;

import java.util.ArrayList;
import java.util.Collection;

import settings.Config;

import logic.common.team.Team;
import logic.nodes.collision.DummyType;
import logic.nodes.nodeSettings.TeamNodeSettings;
import logic.slots.Slot;

import com.jme.scene.DistanceSwitchModel;
import com.jme.scene.Node;
import com.jme.scene.Spatial;
import com.jme.scene.TriMesh;
import com.jme.scene.lod.DiscreteLodNode;

public abstract class SlotNode extends TeamNode {
	
	private static final long serialVersionUID = 1L;
	
	private boolean slotsDone;
	private Collection<Slot> slots;
	private Collection<String> slotNames;
	
	public SlotNode(String path, String title, Node model, TeamNodeSettings settings, Team team) {
		this(path, title, model, settings, team, DummyType.None);
	}
	
	public SlotNode(String path, String title, Node model, TeamNodeSettings settings, Team team, 
			DummyType dummyType) {
		super(path, title, model, settings, team, dummyType);
		
		slots = new ArrayList<Slot>();
		slotNames = new ArrayList<String>();
		
		forceLODNode();
	}
	
	public void registerSlot(Slot slot) {
		slots.add(slot);
	}
	
	public void slotDone(final Slot slot) {
		slots.remove(slot);
		for(TriMesh mesh : slot.getSlotMeshs()) {
			slotNames.add(mesh.getName());
		}
		slotsDone = slots.isEmpty();
		
		ingameState.getThreadPool().addPostRunnable(new Runnable() {
			@Override
			public void run() {
				slot.removeSlotController();
			}
		});
	}
	
	public boolean slotsDone() { return slotsDone; }
	
	public void forceLODNode() {
		if(!Config.get().useLOD()) return;
		
		boolean oldSlotsDone = slotsDone;
		slotsDone = true;
		getLODModel().setActiveChild(getLowIndex());
		slotsDone = oldSlotsDone;
	}
	
	@Override
	protected DiscreteLodNode getDiscreteLodNode(DistanceSwitchModel switchModel) {
		return new DiscreteLodNode("LOD-Node", switchModel) {
			private static final long serialVersionUID = 1L;
			
			@Override
			public void setActiveChild(int index) {
				if(slotsDone) super.setActiveChild(index);
			}
		};
	}
	
	@Override
	public void updateGeometryQuality() {
		super.updateGeometryQuality();
		
		if(slotsDone) {
			Node lowNode = (Node)getLODModel().getChild(getLowIndex());
			
			for(String name : slotNames) {
				Spatial child = lowNode.getChild(name);
				if(child != null) child.removeFromParent();
			}
		}
	}
}